package com.ilxqx.framework.system.controller.hook.inner;

import com.ilxqx.framework.security.po.SimpleUserInfo;
import com.ilxqx.framework.security.util.AuthUtils;
import com.ilxqx.framework.system.controller.hook.PreDelete;
import com.ilxqx.framework.system.controller.hook.PreModify;
import com.ilxqx.framework.system.exception.UpdateDeniedException;
import com.ilxqx.framework.system.util.ReflectionUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

/**
 * 权限操作范围检查
 * @author venus
 */
@Component
@Order(0)
public class PermissionOperationRangeChecker implements PreModify, PreDelete {

    /**
     * 预处理
     *
     * @param entity         实体对象
     * @param form           表单对象
     * @param processingData 处理产生的数据
     */
    @Override
    public void handle(Object entity, Object form, Map<String, Object> processingData) {
        if (this.cannotContinue(entity)) {
            throw new UpdateDeniedException("您没有修改别人数据的权限");
        }
    }

    /**
     * 预处理
     *
     * @param entity 实体对象
     */
    @Override
    public void handle(Object entity) {
        if (this.cannotContinue(entity)) {
            throw new UpdateDeniedException("您没有删除别人数据的权限");
        }
    }

    private boolean cannotContinue(Object entity) {
        if (!AuthUtils.canOperateAllData()) {
            SimpleUserInfo operationUserSimpleInfo = ReflectionUtils.getEntityOperationUserSimpleInfo(entity);
            if (operationUserSimpleInfo == null) {
                // 说明实体类并没有操作用户的说法，直接跳过
                return false;
            }
            // 操作了不是自己的数据
            return !Objects.equals(AuthUtils.getLoggedUserId(), operationUserSimpleInfo.getUserId());
        }
        return false;
    }

}
